package com.kb.service.impl.flow;

import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.kb.common.MeException;
import com.kb.dto.OneStopCode;
import com.kb.dto.flow.*;
import com.kb.dto.HistoricalFactory;
import com.kb.mapper.pg.CrmToK3Mapper;
import com.kb.mapper.pg.FlowMapper;
import com.kb.service.flow.FlowService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.lang.reflect.Field;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Types;
import java.util.*;
import java.util.stream.Collectors;

@DS("MSSQLLIVE")
@Service
public class FlowServiceImpl implements FlowService {

    private static final Logger log = LoggerFactory.getLogger(FlowServiceImpl.class);
    @Resource
    private FlowMapper flowMapper;
    @Resource
    private JdbcTemplate jdbcTemplate;
    @Resource
    private CrmToK3Mapper mapper;


    @Override
    public String querySaleCode(String saleOrg) {
        return mapper.querySaleCode(saleOrg);
    }
    @Override
    public List<HistoricalFactory> getHistoricalFactory(String object) {
        log.info("obj++++++++++++++++++++:" + object);
        // 当object有-时，去掉-后面的字符
        if (Objects.nonNull(object)) {
            if (object.contains("-")) {
                object = object.substring(0, object.indexOf("-"));
            }
            // 当object含有x或者X的时候，去掉x和X
            if (object.contains("X")) {
                object = object.replace("X", "");
            }
            if (object.contains("x")) {
                object = object.replace("x", "");
            }
        }

        List<HistoricalFactory> historicalFactories = flowMapper.queryBankCard(object);
        if (CollectionUtils.isEmpty(historicalFactories)) {
            List<HistoricalFactory> historicalFactoriesTwo = flowMapper.queryBankCardTwo(object);
            historicalFactories.addAll(historicalFactoriesTwo);
        }
        if (CollectionUtils.isEmpty(historicalFactories)) {
            List<HistoricalFactory> historicalFactoriesThree = flowMapper.queryBankCardThree(object);
            historicalFactories.addAll(historicalFactoriesThree);
        }

        List<HistoricalFactory> historicalFactoriesTwo = flowMapper.queryBankCardTwo(object);
        List<HistoricalFactory> historicalFactoriesThree = flowMapper.queryBankCardThree(object);
        historicalFactories.addAll(historicalFactoriesTwo);
        historicalFactories.addAll(historicalFactoriesThree);


        // 把historicalFactory值为惠州的改为大亚湾，泽创改为 KBC，其他不变
        for (HistoricalFactory historicalFactory : historicalFactories) {
            String historicalFactoryValue = historicalFactory.getHistoricalFactory();
            if (historicalFactoryValue != null) {
                historicalFactoryValue = historicalFactoryValue.trim(); // 去除两端空白字符
                if (Objects.equals(historicalFactoryValue, "惠州")) {
                    historicalFactory.setHistoricalFactory("大亚湾");
                } else if (Objects.equals(historicalFactoryValue, "金百泽")) {
                    historicalFactory.setHistoricalFactory("大亚湾");
                } else if (Objects.equals(historicalFactoryValue, "泽创")) {
                    historicalFactory.setHistoricalFactory("KBC");
                } else {
                    historicalFactory.setHistoricalFactory(historicalFactoryValue); // 设置去除空白字符后的值
                }
            }
        }

        // 去除空的historicalFactory
        historicalFactories.removeIf(hf -> Objects.equals(hf.getHistoricalFactory(), "") || hf.getHistoricalFactory() == null);

        if (CollectionUtils.isEmpty(historicalFactories)) {
            return new ArrayList<>();
        }

        // 收集所有 historicalFactory 值
        Set<String> allHistoricalFactories = historicalFactories.stream()
                .map(HistoricalFactory::getHistoricalFactory)
                .collect(Collectors.toSet());

        // 合并 historicalFactory 值到每一条记录中
        String mergedHistoricalFactory = String.join(",", allHistoricalFactories);

        // 使用 toMap 去重
        // 过滤掉整个对象为 null 的情况
        // 过滤掉 getCode 为 null 的情况

        return new ArrayList<>(historicalFactories.stream()
                .filter(Objects::nonNull) // 过滤掉整个对象为 null 的情况
                .filter(factory -> factory.getCode() != null) // 过滤掉 getCode 为 null 的情况
                .collect(Collectors.toMap(
                        HistoricalFactory::getCode,
                        factory -> new HistoricalFactory(factory.getCode().trim(), mergedHistoricalFactory),
                        (existing, replacement) -> existing
                ))
                .values());
    }


    @Override
    public List<DisposalOrderNumber> getDisposalOrderNumber(String object) {
        //将查询结果封装到list中
        List<DisposalOrderNumber> list = flowMapper.queryCustomerComplaint(object);
        return list;
    }

    @Override
    public String getOneStopCode(OneStopCode keyword) throws MeException{
        String businessType = keyword.getBusinessType();
        String contractType = keyword.getContractType();
        log.info("businessType:{}", businessType);
        log.info("contractType:{}", contractType);
        String contract;
        switch (contractType) {
            case "总合同":
                contract = "M";
                break;
            case "分开合同":
                contract = "E";
                break;
            default:
                throw new MeException("无效的 contractType，请使用：总合同、分开合同 ，您的contractType: " + contractType);
        }
        String business = Arrays.stream(businessType.split(","))
                .map(this::convertBusinessType)
                .collect(Collectors.joining());

        try (Connection connection = jdbcTemplate.getDataSource().getConnection();
             /**
              * 合同类型  M E
              * 业务类型 1 2 3 4 5 6 8
              * E52003-24
              */
             CallableStatement callableStatement = connection.prepareCall("{call UpdateAndReturnCode(?)}")) {

            // 注册输出参数
            callableStatement.registerOutParameter(1, Types.NVARCHAR);

            // 执行存储过程
            callableStatement.execute();

            // 获取输出参数的值
            String string = callableStatement.getString(1);
            log.info("string:{}", string);
            return contract + string + "-" + business;

        } catch (SQLException e) {
            log.error("Error executing stored procedure GetNextDailySequence", e);
            throw new MeException("Error executing stored procedure GetNextDailySequence", e);
        }
    }

    private String convertBusinessType(String businessType) {
        switch (businessType) {
            case "CAD":
                return "1";
            case "PCB":
                return "2";
            case "元器件":
                return "3";
            case "PCBA":
                return "4";
            case "EES":
                return "5";
            case "方案":
                return "8";
            default:
                throw new MeException("无效的 businessType，请使用：CAD,PCB,元器件,PCBA,EES,方案，您的businessType: " + businessType);
        }
    }

    @Override
    public String getOneStopCodeRandom(String keyword) {
        try (Connection connection = jdbcTemplate.getDataSource().getConnection();
             CallableStatement callableStatement = connection.prepareCall("{call UpdateAndReturnCode(?)}")) {

            // 注册输出参数
            callableStatement.registerOutParameter(1, Types.NVARCHAR);

            // 执行存储过程
            callableStatement.execute();

            // 获取输出参数的值
            return callableStatement.getString(1);

        } catch (SQLException e) {
            log.error("Error executing stored procedure GetNextDailySequence", e);
            throw new RuntimeException("Error executing stored procedure GetNextDailySequence", e);
        }
    }

    @Override
    public List<BalanceReceivable> getBalanceReceivable(String keyword) {
        return flowMapper.getBalanceReceivable(keyword);
    }

    public static void main(String[] args) {
        DisposalOrderNumber disposalOrderNumber = new DisposalOrderNumber();
        disposalOrderNumber.setCompNumber("1111");
        // 获取 DisposalOrderNumber 类的所有字段
        Field[] fields = DisposalOrderNumber.class.getDeclaredFields();
        for (Field field : fields) {
            // 设置字段可访问，以确保可以访问私有字段
            field.setAccessible(true);
            // 获取字段的值
            Object value = null;
            try {
                value = field.get(disposalOrderNumber);
            } catch (IllegalAccessException e) {
                throw new RuntimeException(e);
            }
            // 检查字段的值是否为空
            if (value != null) {
                System.out.println("Field: " + field.getName() + ", Value: " + value);
            }
        }

    }

    @Override
    public List<PartsConsumables> getITPartsConsumables(String keyword) {
        return flowMapper.getITPartsConsumables(keyword);
    }

    @Override
    public List<CrmCustomerInfo> getCrmCustomerInfo(String keyword, String userName_eq) {
        //判断userName_eq是否为空，为空则返回响应字段值为自定义的字段
        ArrayList<CrmCustomerInfo> objects = new ArrayList<>();
        if (Objects.isNull(userName_eq)) {
            objects.add(new CrmCustomerInfo());
            return objects;
        }
        return flowMapper.getCrmCustomerInfo(keyword, userName_eq);
    }
}
